<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>canvas</title>
    <script src="./js/initShader.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        canvas {
            margin: 50px auto 0;
            display: block;
            background: yellow;
        }
    </style>
</head>

<body>
    <canvas id="gl-canvas" width="500" height="500">
        Please use a browser that supports "canvas".
    </canvas>
    <script>
        var canvas = document.getElementById("gl-canvas");
        var gl = canvas.getContext("webgl");

        // 定义顶点着色器
        var VSHADER_SOURCE = `
        attribute vec4 aPosition;
        void main(){
            gl_PointSize = 30.0;
            gl_Position = aPosition;
        }
      `;

        // 定义片元着色器
        var FSHADER_SOURCE = `
        precision mediump float;
        void main(){
            gl_FragColor = vec4(1.0,0.0,0.0,1.0);
        }
      `;


        // 创建着色器程序
        const program1 = initShader(gl, VSHADER_SOURCE, FSHADER_SOURCE);

        // 获取顶点着色器中的变量
        var aPosition = gl.getAttribLocation(program1, "aPosition");

        gl.vertexAttrib1f(aPosition, 0.0);
        gl.drawArrays(gl.POINTS, 0, 1);
        const points = [];
        canvas.onmousemove = function (event) {
            var x = event.clientX;
            var y = event.clientY;
            console.log(x, y);
            // 获取canvas的宽高
            var rect = event.target.getBoundingClientRect();
            console.log(rect);
            const domx = x-rect.left;
            const domy = y-rect.top;
            const halfWidth = canvas.offsetWidth/2;
            const halfHeight = canvas.offsetHeight/2;
            const clickX = (domx-halfWidth)/halfWidth;
            const clickY = (halfHeight-domy)/halfHeight;
            console.log(clickX,clickY);
    
            points.push({
                clickX,clickY
            });
            for (let index = 0; index < points.length; index++) {
               gl.vertexAttrib2f(aPosition, points[index].clickX,points[index].clickY);
               gl.drawArrays(gl.POINTS, 0, 1);
                
            }
            // gl.vertexAttrib2f(aPosition, clickX,clickY);
            // gl.drawArrays(gl.POINTS, 0, 1);
        }
    </script>
</body>

</html>